package edu.misaka.moe.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;

import edu.misaka.moe.dao.UserDaoImpl;
import edu.misaka.moe.domain.Hobby;
import edu.misaka.moe.domain.Native;
import edu.misaka.moe.domain.Page;
import edu.misaka.moe.domain.UMQueryKeyword;
import edu.misaka.moe.domain.User;
import edu.misaka.moe.domain.UserDetail;
import edu.misaka.moe.service.HobbyServiceImpl;
import edu.misaka.moe.service.NativeServiceImpl;
import edu.misaka.moe.service.UserServiceImpl;
import edu.misaka.moe.service.iface.HobbyService;
import edu.misaka.moe.service.iface.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/user.servlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
    public UserServlet() {
        super();
        
    }
    private UserService userService=new UserServiceImpl();
    private HobbyService hobbyService=new HobbyServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html ;charset=utf-8");
		
		//取得所需要的公共信息
		PrintWriter out=response.getWriter();
		String param=request.getParameter("param");
		String id=request.getParameter("id");
		
		String username=null==request.getParameter("userName")?"":request.getParameter("userName");
		String name=null==request.getParameter("Name")?"":request.getParameter("Name");
		String password=request.getParameter("password");
		String sex=null==request.getParameter("sex")?"":request.getParameter("sex");
		String email=request.getParameter("email");
		String cityCode=request.getParameter("cityCode");
		String hobby=null==request.getParameter("hobby")?"":request.getParameter("hobby");
		String[] favs=request.getParameterValues("fav");
		String currentPage=null==request.getParameter("currentPage")?"1":request.getParameter("currentPage");
		//登录验证
		if(Objects.equals("checkName", param)) {
			
		}
		if(Objects.equals("login", param)) {
			username=request.getParameter("username");
			password=request.getParameter("password");
			UserService userservice=new UserServiceImpl();
			boolean flag=userservice.login(username, password);
			
			String isCookie=null==request.getParameter("isCookie")?"no":request.getParameter("isCookie");
			if(flag) {
				 HttpSession session=request.getSession();
				session.setAttribute("name", "misaka");
				if(isCookie.equals("yes")) {
					Cookie okcookie=new Cookie("web","www.misaka.com");
					okcookie.setMaxAge(60);
					response.addCookie(okcookie);
				}
				request.getRequestDispatcher("views/main.jsp").forward(request, response);
			}else {
				request.getRequestDispatcher("misaka.jsp").forward(request, response);
				
			}
		}
		//点击注册按钮跳转注册页面
		if(Objects.equals("register", param)) {
			List<Hobby> hobbyies=new HobbyServiceImpl().getHobbies();
			List<Native> nat=new NativeServiceImpl().getProvince();
			request.setAttribute("hobby", hobbyies);
			request.setAttribute("natives", nat);
			request.getRequestDispatcher("register.jsp").forward(request, response);
			
		}
		//点击完成注册按钮提交用户信息到数据库
		if(Objects.equals("upuser", param)) {

			User user=new User(0,username,name,password,sex,email);
			UserDetail ud=new UserDetail(0,cityCode,String.join(",", favs),0);
			boolean flag=new UserServiceImpl().register(user, ud);
			if(flag) {
				response.sendRedirect("misaka.jsp");
			}else {
			
				out.print("<script>alert('注册失败 请确认信息是否正确！');window.location.href='init.servlet");
				out.flush();
				out.close();

			}
		}
		
		//根据省来查询到城市用ajax
		if(Objects.equals("city", param)) {
			String code=request.getParameter("code");
			List<Native> list=new NativeServiceImpl().getCity(code);
			Map<String,Object> map=new HashMap<>();
			if(null==list||list.size()==0) {
				map.put("msg", "no data");
			}else {
				map.put("msg", "success");
				map.put("result", list);
				
			}
			String json=JSONObject.toJSONString(map);
			
			out.println(json);
			out.flush();
			out.close();
		}
		
		if(Objects.equals("init", param)) {
			Page<List<Map<String,Object>>> page=new Page<>(Integer.valueOf(currentPage));
			List<Hobby> hobbyList=hobbyService.getHobbies();
			UMQueryKeyword qk=null;
			if(Objects.equals("", name) && Objects.equals("", sex) && Objects.equals("", hobby)) {
				userService.showByPage(page);		//查询所有用户
				userService.getTotalRow(page);
			}else {
				qk=new UMQueryKeyword(name,sex,hobby);
				userService.showByPage(page,qk);	//即席查询
				userService.getTotalRow(page,qk);	
			}
			page.setTotalPage(0==page.getTotalRow()%page.getRowNumber()?page.getTotalRow()/page.getRowNumber():page.getTotalRow()/page.getRowNumber()+1);
			hobbyService.setHobbyName(page.getPageData());
			request.setAttribute("users",page.getPageData());
			request.setAttribute("page", page);
			request.setAttribute("hobbies", hobbyList);
			if(null!=qk) {
				request.setAttribute("querykey", qk);
			}
			request.getRequestDispatcher("views/userManager.jsp").forward(request, response);
		}
		
		
		
	}




	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}
